<?php

namespace app\order\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\api\logic\ApiOrderLogic;
use app\api\logic\ApiOrdercheckLogic;
use app\api\logic\FreightLogic;
use app\api\logic\FeiShuTalkLogic;
use app\order\logic\OrderSourceLogic;
use app\api\logic\ShopyLogic;
use app\order\logic\OrderReportSkuLogic;
use app\api\logic\FeiShuMessageLogic;
use app\data\util\HttpUtil;
use app\api\logic\CheckLogic;

class DisputesLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\order\model\Order();
    }

    
    /**
    * @desc    更新状态以及附加数据
    * @author  zhangheng
    */
    public function DisputeToOrdersShopify()
    {
        $t1       = microtime(true);
        $count = Db::name('order_dispute_api')
            ->where('disputetime',">=",time()-3600*24*30*4)
            ->count();
            // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_api')
                ->field('
                        id,
                        shop_id,
                        order_id,initiated_at,
                        status
                    ')
                ->where('disputetime',">=",time()-3600*24*30*4)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                //更新会话
                if(!empty($order_customer['email'])){
                    $conversations = Db::name('conversations')
                        ->where('email',$order_customer['email'])
                        ->count();
                }else{
                    $conversations = 0;
                }
                //发货时间
                $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                //签收时间
                $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('update_time desc')->find();
                $track_status = $order_track['latest_status'] ?? "null";
                if(strpos($track_status,'Delivered') !== false){
                    $SignInTime = $order_track['update_time'];
                }else{
                    $SignInTime = '';
                }

                //找到争议
                $update = [
                    'SignInTime' => $SignInTime,
                    'conversations' => $conversations,
                    'financial_status' => $order_achievement['financial_status'] ?? "",
                    'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                    'tracking_number' => $order_achievement['tracking_number'] ?? "",
                    'disputetime' => $this->dateTimeStr($v['initiated_at']),
                    'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                ];
                
                Db::name('order_dispute_api')
                    ->where('id',$v['id'])
                    ->update($update);
                //修改争议金额
                $v['status'] = $this->ChangeState($v['status'],'shopify');
                $v['dispute'] = $this->ChangeAmount($v['status'],'shopify');
                $update_achievement = [
                    'disputeapi_type' => "shopify",
                    'disputeapi_status' => $v['status'] ??"暂无争议",
                    'dispute' => $v['dispute'],
                ];
                // halt($update_achievement);
                Db::name('order_achievement')
                    ->where('order_id',$order_achievement['order_id'])
                    ->update($update_achievement);
                $executedCountsu++;
                    
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    
    //争议数据对应到订单afterpay
    public function DisputeToOrdersAfterpay(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_afterpay')
            ->where('disputetime',">=",time()-3600*24*30*4)
            ->where('order_id',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_afterpay')
                ->field('
                        id,
                        api_type,
                        type,
                        order_id,
                        status,createdAt,
                        merchantOrderId
                    ')
                    ->where('disputetime',">=",time()-3600*24*30*4)
                    ->where('order_id',">",0)
                    ->order('id desc')
                    ->paginate([  
                        'list_rows' => $pageSize,
                        'page' => $i,
                    ])->toarray();
            
            foreach ($list['data'] as $v){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'afterpay');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'afterpay');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    
                    //发货时间
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //签收时间
                    $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('update_time desc')->find();
                    $track_status = $order_track['latest_status'] ?? "null";
                    if(strpos($track_status,'Delivered') !== false){
                        $SignInTime = $order_track['update_time'];
                    }else{
                        $SignInTime = '';
                    }
                    
                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'SignInTime' => $SignInTime,
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => $v['createdAt'],
                    ];
                    Db::name('order_dispute_afterpay')
                        ->where('id',$v['id'])
                        ->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    
    
    //争议数据对应到订单Airwallex
    public function DisputeToOrdersAirwallex(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_airwallex')
            ->where('disputetime',">=",time()-3600*24*30*4)
            ->where('order_id',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_airwallex')
                ->field('
                        id,
                        status,
                        order_id,created_at,
                        airwallex_id
                    ')
                ->where('disputetime',">=",time()-3600*24*30*4)
                ->where('order_id',">",0)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'airwallex');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'airwallex');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => "airwallex",
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    
                    //签收时间
                    $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('update_time desc')->find();
                    $track_status = $order_track['latest_status'] ?? "null";
                    if(strpos($track_status,'Delivered') !== false){
                        $SignInTime = $order_track['update_time'];
                    }else{
                        $SignInTime = '';
                    }

                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'SignInTime' => $SignInTime,
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['created_at']),
                        'createtime' => $order_achievement['createtime'],
                    ];
                    Db::name('order_dispute_airwallex')
                        ->where('id',$v['id'])
                        ->update($update);
                            
                    $executedCountsu++;
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_dispute_airwallex-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    
    }

    
    //争议数据对应到订单Paypal
    public function DisputeToOrdersPaypal(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_paypal')
            ->where('disputetime',">=",time()-3600*24*30*4)
            ->where('order_id',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_paypal')
                ->field('
                        id,
                        api_type,
                        type,
                        status,
                        order_id,create_time,
                        seller_transaction_id
                    ')
                ->where('disputetime',">=",time()-3600*24*30*4)
                ->where('order_id',">",0)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'paypal');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'paypal');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    
                    //签收时间
                    $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('update_time desc')->find();
                    $track_status = $order_track['latest_status'] ?? "null";
                    if(strpos($track_status,'Delivered') !== false){
                        $SignInTime = $order_track['update_time'];
                    }else{
                        $SignInTime = '';
                    }

                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'SignInTime' => $SignInTime,
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['create_time']),
                    ];
                    Db::name('order_dispute_paypal')
                        ->where('id',$v['id'])
                        ->update($update);

                    $executedCountsu++;
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    
    //争议数据对应到订单Stripe
    public function DisputeToOrdersStripe(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_stripe')
            ->where('disputetime',">=",time()-3600*24*30*4)
            ->where('order_id',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_stripe')
                ->field('
                        id,
                        api_type,
                        type,
                        status,
                        order_id,create_time,
                        payment_intent
                    ')
                ->where('disputetime',">=",time()-3600*24*30*4)
                ->where('order_id',">",0)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'stripe');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'stripe');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ??"暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }

                    //签收时间
                    $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('update_time desc')->find();
                    $track_status = $order_track['latest_status'] ?? "null";
                    if(strpos($track_status,'Delivered') !== false){
                        $SignInTime = $order_track['update_time'];
                    }else{
                        $SignInTime = '';
                    }

                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'SignInTime' => $SignInTime,
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['create_time']),
                    ];
                    Db::name('order_dispute_stripe')
                        ->where('id',$v['id'])
                        ->update($update);

                    $executedCountsu++;
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function dateTimeStr($dateTimeStr) {  
        $posT = strpos($dateTimeStr, 'T');  
        if ($posT !== false) {  
            $datePart = substr($dateTimeStr, 0, $posT);  
            $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '-', $posT + 1) - ($posT + 1));  
            $formattedDateTime = $datePart . ' ' . $timePart;  
            $formattedDateTime = strtotime($formattedDateTime);
            if (!$formattedDateTime) {  
                $datePart = substr($dateTimeStr, 0, $posT);  
                $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '+', $posT + 1) - ($posT + 1));  
                $formattedDateTime = $datePart . ' ' . $timePart;  
                $formattedDateTime = strtotime($formattedDateTime);
                return $formattedDateTime;
            }else{
                return $formattedDateTime;
            }
        } else {  
            return 0;
        }  
    }

    

    /**
    * @desc    通道状态
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeState($status,$type)
    {
        if($type == 'stripe'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'paypal'){
            switch ($status) {
                case 'WAITING_FOR_SELLER_RESPONSE':
                    $status = '待处理';
                    break;
                case 'UNDER_REVIEW':
                    $status = '审核中';
                    break;
                case 'RESOLVED':
                    $status = '争议赢';
                    break;
                case 'LOST':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'afterpay'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'shopify'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'airwallex'){
            switch ($status) {
                case 'LOST':
                    $status = '争议输';
                    break;
                case 'ACCEPTED':
                    $status = '争议输';
                    break;
                case 'WON':
                    $status = '争议赢';
                    break;
                case 'CHALLENGED':
                    $status = '审核中';
                    break;
                default:
                    $status = '其他';
            }
        }
        return $status;
    }

    /**
    * @desc    通道金额
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeAmount($status,$type)
    {
        //美金
        $dispute = 0;
        if($status == '争议输'){
            switch ($type) {
                case 'stripe':
                    $dispute = 17;
                    break;
                case 'paypal':
                    $dispute = 8;
                    break;
                case 'shopify':
                    $dispute = 15;
                    break;
                case 'afterpay':
                    $dispute = 15;
                    break;
                case 'airwallex':
                    $dispute = 15;
                    break;
                default:
                    $dispute = 15;
            }
        }
        return $dispute;
    }
    
}
